import 'package:casdon/modules/lifeCircle/data/model/life_subject_module.dart';
import 'package:casdon/modules/lifeCircle/domain/states/life_tab_state.dart';
import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

// 状态控制器
class LifeTabControllerNotifier extends AsyncNotifier<LifeTabState> {
  @override
  Future<LifeTabState> build() async {
    return _fetchData(0);
  }

  Future<void> refresh() async {
    try {
      final newState = await _fetchData(0);
      state = AsyncValue.data(newState);
    } catch (e, st) {
      state = AsyncValue.error(e, st);
    }
  }

  Future<LifeTabState> _fetchData(int type) async {
    try {
      final ret = await ref
          .read(lifeSujectListUsecaseProvider)
          .execute(type: type);
      final netData = LifeSubjectModule.listFromApi(ret);
      netData.sort((a, b) => a.sort.compareTo(b.sort));

      // 添加本地前两个标签："关注"和"推荐"
      // 注意：这两个标签是特殊的，不会出现在 API 返回的列表中
      final staticTabs = <LifeSubjectModule>[];

      final allTabs = [...staticTabs, ...netData];
      return LifeTabState(data: allTabs, currentIndex: 0);
    } catch (e, st) {
      return LifeTabState.initial();
    }
  }

  // 切换标签
  void setIndex(int index) {
    final currentValue = state.value;
    if (currentValue != null) {
      state = AsyncValue.data(currentValue.copyWith(currentIndex: index));
    }
  }
}
